package com.zdp.剑指offer;

public class 替换空格 {
    public static void main(String[] args) {
        替换空格 demo = new 替换空格();
        StringBuffer str = new StringBuffer("We are Happy");
        String str1 = demo.replaceSpace(str);
        System.out.println(str1);

    }

    public String replaceSpace(StringBuffer str) {
        int index1 = str.length()-1;
        int count=0;
        for(int i=0;i<str.length();i++){
            if(str.charAt(i)==' '){
                count++;
            }
        }

        str.setLength(str.length()+count*2);
        int index2 = str.length()-1;

        //从后往前替换，会要插入的字符腾出位置
        for(;index1>=0;index1--){
            if(str.charAt(index1)!=' '){
                str.setCharAt(index2,str.charAt(index1));
                index2--;
            }else{
                //也可以用replace
                /*
                * str.replace(index2-2,index2+1,"%20");
                * index2-3;
                * */
                str.setCharAt(index2,'0');
                index2--;
                str.setCharAt(index2,'2');
                index2--;
                str.setCharAt(index2,'%');
                index2--;

            }
        }

        return str.toString();
    }
}
